<?php

class NodeController extends Controller
{
	public $hasPoll; 
	
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'cite', 'userlist'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array(Yii::app()->params['admin']),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		$tags = Tag::model()->findAllByAttributes(array('nid'=>$id));
  
       	// 页面的链接映射
		$nodeMapping = NodeMapping::model()->with('snode')->findAll('mid = :Id', array(':Id'=>$id));
		// 页面的引用
		$cite = NodeMapping::model()->count('sid = :Id', array(':Id'=>$id));
		
		// 页面统计
		$pageCount = new CountVisit;
		$count = $pageCount->findByAttributes( array(
			'ip'=>Yii::app()->request->userHostAddress,
			'nid'=>$id,
		));
		if ($count){
			$time = time() - $count->time;
			if ($time > DefineBox::TIME_COUNTVISIT_LIMIT){
				$model->visit++;
				$model->save();
				// 更新页面统计
				$count->time = time();
				$count->save();
			}
		}
		else{
			$pageCount->ip =  Yii::app()->request->userHostAddress;
			$pageCount->nid = $id;
			$pageCount->time = time();
			$pageCount->save();
			$model->visit++;
			$model->save();
		}
		
		// 投票表单
		$poll = Poll::model()->findByAttributes(array('nid'=>$id, 'status'=>1));
		if ($poll){
			if($poll->finish_time < time()){
				$poll->status = 0;
				$poll->save();
				$total = count(PollVote::model()->findAllByAttributes(array('pid'=>$poll->id)));
	            $yes= count(PollVote::model()->findAllByAttributes(array('pid'=>$poll->id, 'value'=>1)));
	            $score = $yes/$total;
                $cpl=sprintf('%.0f%%',$score*100);
                if($cpl>0.66){
                	$model->status = DefineBox::NODE_STATUS_NORMAL;
                	$model->level=$poll->value;
                }
                $model->save();
	            $this->hasPoll = false;
            }
			else{
				$this->hasPoll = true;
			}
		}
		
		$modelVote=new PollVote;
		if(isset($_POST['PollVote'])){
			$modelVote->uid = yii::app()->user->id;
			$modelVote->attributes = $_POST['PollVote'];
			$modelVote->pid = $poll->id;
			$modelVote->save();
			//给用户加积分
			$user= User::model()->findByPk(Yii::app()->user->id);
			$user->score=$user->score+DefineBox::USER_SCORE_VOTE;
			$user->save();
	    }
		
	    // 输出到视图
		$this->render('view',array(
			'model'=>$model,
			'tags'=>$tags,
			'type'=>HandleBox::getNodeType($model->tid),
			'nodeMapping'=>$nodeMapping,
			'poll'=>$poll,
			'modelVote'=>$modelVote,
			'cite'=>$cite,
		));
		
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($tid)
	{
		$model=new Node;
		$nodeMeta = new NodeMeta;
		$virtual = new Virtual;
        $cats = Category::model()->findAllByAttributes(array('fid'=>$tid));
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Node'])){
			$model->attributes=$_POST['Node'];
			$model->uid = Yii::app()->user->id;
			$model->tid = $tid;
			$model->status =DefineBox::NODE_STATUS_NORMAL;
			$model->level = 0;
			$model->create_time = $model->update_time = time();
			if ($model->save()){
				// 时间
				if (isset($_POST['NodeMeta'])){
					$nodeMeta->nid =$model->id;
					$nodeMeta->key = 'time';
					$nodeMeta->value = $_POST['NodeMeta']['value'];
					$nodeMeta->save();
				}
				// 作者记录
				$nodeUser = new NodeUser;
				$nodeUser->nid = $model->id;
				$nodeUser->uid = Yii::app()->user->id;
				$nodeUser->save(false);
				
				$handle = new HandleBox;
				// 创建历史记录
				$handle->nodeRevisionHandle($model->id, null, $_POST['Node']['body']);
				
				if (isset($_POST['Virtual']) and $virtual->validate()){
					// 使用HandleBox中的tagHandle处理tag
					if (isset($_POST['Virtual']['tag'])){
						$tag = str_replace(array("，", " "), ",",$_POST['Virtual']['tag']);
						$tagArray = explode(",", $tag);
						$handle->tagHandle($model->id, $model->tid, $tagArray);
					}
					// 处理映射链接
					$dataArray = array();
					if (!empty($_POST['Virtual']['event'])){
						$event = str_replace(array("，", " "), ",",$_POST['Virtual']['event']);
						$dataArray[DefineBox::EVENT_TYPE_CODE] = explode(',', $event);
					}
					if (!empty($_POST['Virtual']['scene'])){
						$scene = str_replace(array("，", " "), ",",$_POST['Virtual']['scene']);
						$dataArray[DefineBox::SCENE_TYPE_CODE] = explode(',', $scene);
					}
					if (!empty($_POST['Virtual']['role'])){
						$role = str_replace(array("，", " "), ",",$_POST['Virtual']['role']);
						$dataArray[DefineBox::ROLE_TYPE_CODE] = explode(',', $role);
					}
					if (!empty($_POST['Virtual']['object'])){
						$object = str_replace(array("，", " "), ",",$_POST['Virtual']['object']);
						$dataArray[DefineBox::OBJECT_TYPE_CODE] = explode(',', $object);
					}
					if (!empty($_POST['Virtual']['pedia'])){
						$pedia = str_replace(array("，", " "), ",",$_POST['Virtual']['pedia']);
						$dataArray[DefineBox::PEDIA_TYPE_CODE] = explode(',', $pedia);
					}
					if (!empty($dataArray)){
						$handle->nodeMappingHandle($model->id, $dataArray);
					}
				}
				//给用户加积分
				$user= User::model()->findByPk(Yii::app()->user->id);
				$user->score=$user->score+DefineBox::USER_SCORE_CNODE;
				$user->save();
				Yii::app()->user->setFlash('score',"操作成功，您的贡献值增加了".DefineBox::USER_SCORE_CNODE."分");
				$this->redirect(array('view','id'=>$model->id));
			}
		}
			
		$this->render('create',array(
			'model'=>$model,
			'nodeMeta' => $nodeMeta,
			'virtual'=>$virtual,
		    'cats'=>$cats,
			'type'=>HandleBox::getNodeType($tid),
		    'tid'=>$tid,
		    
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$nodeMapping = NodeMapping::model()->with('snode')->findAll('mid = :Id', array(':Id'=>$id));
		$tags = Tag::model()->findAllByAttributes(array('nid'=>$id));
		$cats = Category::model()->findAllByAttributes(array('fid'=>$model->tid));
		$virtual = new Virtual;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Node']))
		{
			$bodyOld = $model->body;
			$model->attributes=$_POST['Node'];
			if ($model->create_time == 0){
				$model->create_time = $model->update_time = time();
			}
			else{
				$model->update_time = time();
			}
			$model->status = DefineBox::NODE_STATUS_NORMAL;//经过编辑的空内容成为有效内容
			if($model->update()){
				// 作者记录
				$nodeUser = NodeUser::model()->findByAttributes(array('nid'=>$id, 'uid'=>Yii::app()->user->id));
				if ($nodeUser == null){
					$nodeUser = new NodeUser;
					$nodeUser->nid = $id;
					$nodeUser->uid = Yii::app()->user->id;
					$nodeUser->save(false);
				}
				
				$handle = new HandleBox;
				// 创建历史记录
				$handle->nodeRevisionHandle($id, $bodyOld, $_POST['Node']['body']);
				
				if (isset($_POST['Virtual']) and $virtual->validate()){
					// 使用HandleBox中的tagHandle处理tag
					if (isset($_POST['Virtual']['tag'])){
						$tag = str_replace(array("，", " "), ",",$_POST['Virtual']['tag']);
						$tagArray = explode(",", $tag);
						$handle->tagHandle($model->id, $model->tid, $tagArray);
					}
					// 处理映射链接
					$dataArray = array();
					if (!empty($_POST['Virtual']['event'])){
						$event = str_replace(array("，", " "), ",",$_POST['Virtual']['event']);
						$dataArray[DefineBox::EVENT_TYPE_CODE] = explode(',', $event);
					}
					if (!empty($_POST['Virtual']['scene'])){
						$scene = str_replace(array("，", " "), ",",$_POST['Virtual']['scene']);
						$dataArray[DefineBox::SCENE_TYPE_CODE] = explode(',', $scene);
					}
					if (!empty($_POST['Virtual']['role'])){
						$role = str_replace(array("，", " "), ",",$_POST['Virtual']['role']);
						$dataArray[DefineBox::ROLE_TYPE_CODE] = explode(',', $role);
					}
					if (!empty($_POST['Virtual']['object'])){
						$object = str_replace(array("，", " "), ",",$_POST['Virtual']['object']);
						$dataArray[DefineBox::OBJECT_TYPE_CODE] = explode(',', $object);
					}
					if (!empty($_POST['Virtual']['pedia'])){
						$pedia = str_replace(array("，", " "), ",",$_POST['Virtual']['pedia']);
						$dataArray[DefineBox::PEDIA_TYPE_CODE] = explode(',', $pedia);
					}
					if (!empty($dataArray)){
						$handle->nodeMappingHandle($model->id, $dataArray);
					}
				}
				//给用户加积分
				$user= User::model()->findByPk(Yii::app()->user->id);
				$user->score=$user->score+DefineBox::USER_SCORE_ENODE;
				$user->save();
				Yii::app()->user->setFlash('score',"贡献值+".DefineBox::USER_SCORE_ENODE);
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		    'cats'=>$cats,
			'tags'=>$tags,
			'nodeMapping'=>$nodeMapping,
			'virtual'=>$virtual,
			'type'=>HandleBox::getNodeType($model->tid),
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			if ($model){
				$model->status =DefineBox::NODE_STATUS_DELETE;
				$model->save(false);
			}
			//删减用户积分
			$user= User::model()->findByPk(Yii::app()->user->id);
			$user->score=$user->score+DefineBox::USER_SCORE_DNODE;
			$user->save();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex($tid = null)
	{
		if ($tid!= null){
			$dataProvider = new CActiveDataProvider('Node', array(
				'criteria'=>array(
					'condition'=>'tid = :Tid and status > '.DefineBox::NODE_STATUS_EMPTY ,
			        'params'=>array(':Tid'=>$tid),
					'order'=>'id DESC',
				),
				'pagination'=>array('pageSize'=>20),
			));
		}
		else{
			$dataProvider=new CActiveDataProvider('Node');
		}
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
			'type'=>HandleBox::getNodeType($tid),
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Node('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Node']))
			$model->attributes=$_GET['Node'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Node::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='node-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * 引用列表
	 */
	public function actionCite($sid)
	{
		$title = Node::model()->findByPk($sid)->title;
		$dataProvider = new CActiveDataProvider('NodeMapping', array(
			'criteria'=>array(
				'condition'=>'sid = :Sid',
				'params'=>array(':Sid'=>$sid),
				'with'=>'mnode',
			),
			'pagination'=>array('pageSize'=>20),
		));
		
		$this->render('cite',array(
				'dataProvider'=>$dataProvider,
				'title'=>$title,
		));
	}
	
	/**
	 * 作者列表
	 */
	public function actionUserList($id)
	{
		$node = Node::model()->findByPk($id);
		$dataProvider = new CActiveDataProvider('NodeUser', array(
			'criteria'=>array(
				'condition'=>'nid = :Nid',
				'params'=>array(':Nid'=>$id),
				'with'=>'user',
			),
			'pagination'=>array('pageSize'=>30),
		));
		$dataProvider->setId($id);
		
		$this->render('userlist', array(
			'dataProvider'=>$dataProvider,
			'node'=>$node,
		));
	}
	

}
